package com.bjb.vr.client.config;

import cn.hutool.core.util.IdUtil;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.bjb.vr.client.properties.VersionProperties;
import com.bjb.vr.common.utils.ZkClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @description: 读取自定义配置文件信息
 * @author: HuJingBo
 * @time: 2022/2/21 09:14
 */
@Order(1)
@Component
@Slf4j
@ConditionalOnProperty(value = "zookeeper.monitor.enable", matchIfMissing = false)
public class InitStarter implements CommandLineRunner {

    @Autowired
    private NacosDiscoveryProperties discoveryProperties;

    @Autowired
    private Environment environment;

    @Autowired
    private CuratorFramework zkClient;

    @Resource
    private VersionProperties versionProp;

//    @Autowired
//    private Map<String, String> arthasConfigMap;


    @Override
    public void run(String... args) throws Exception {
        log.info("项目启动信息 ......");
        log.info("当前Git版本号(commitId):{}", versionProp.getGit());
        log.info("当前Jenkins版本号(buildId):{}", versionProp.getJenkins());
        log.info("当前项目版本号(imageTag):{}", versionProp.getProject());
    }

    /**
     * 可以添加更多信息到zookeeper
     */
    @PostConstruct
    public void init() {
        String ip = discoveryProperties.getIp();
        String port = environment.getProperty("server.port");
//        String agentId = arthasConfigMap.get("agent-id");
        String agentId = IdUtil.objectId();
        String serviceName = discoveryProperties.getService();
        String info = String.format("%s;%s;%s;%s", serviceName, ip, port, agentId);
        String path = "/servers/" + serviceName + "/" + serviceName + ";" + ip + ";" + port + ";" + agentId;
        ZkClientUtil.createTempNode(zkClient, path, info);
    }
}
